<template>
  <div class="container-cc">
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field v-model.trim="form.name" name="name" label="家长姓名" placeholder="家长姓名"
          :rules="[{ required: true, message: '请填写家长姓名' }]" />
        <van-field v-model.trim="form.phoneNumber" type="number" name="phoneNumber" label="手机号" placeholder="手机号"
          :rules="[{ validator, required: true, message: '请填写正确的手机号' }]" />
      </van-cell-group>
      <div class="addbtn">
        <van-button round block type="primary" native-type="submit" :disabled="!(form.name && validator(form.phoneNumber))"
          @click="resolveToken">
          新增子女
        </van-button>
      </div>
    </van-form>

  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { onMounted } from 'vue'
import { isFirstLogin, wxLogin, wxOpenId } from '@/api/login';
import { showToast } from 'vant';

const validator = (val) => /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(val);

const router = useRouter()
const form = reactive({
  phoneNumber: '',
  name: '',
})


//  判断是否是首次登录
const handleIsFirstLogin = async (openId) => {
  const { code, data } = await isFirstLogin({ openId });
  if (code == 200) {
    if (data && data.length > 0) {
      try {
        localStorage.setItem('parentId', JSON.stringify(data[0].parentId));
        localStorage.setItem('userInfo', JSON.stringify(data));
      } catch (ev) { }
    } else {
      //  调整页面 让用户输入内容
      router.push({ path: '/InformationCollection' })
    }
  }
}

//  获取并设置 token
const resolveToken = async () => {
  const openId = localStorage.getItem('openId');
  //  登录 获取 token
  const { code, data } = await wxLogin({
    grant_type: 'wechat',
    phoneNumber: form.phoneNumber,
    openId,
    name: form.name,
    client_id: 'admin',
    client_secret: '123456',
    timestamp: '1713495821000',
    orgId: '550655738519750597'
  });

  if (code === 200) {
    const token = data.token;
    if (token) {
      localStorage.setItem('token', token);
      await handleIsFirstLogin(openId)
      //  登录成功 跳转到首页
      router.push({ path: '/childrenInfo' , query: { status: 'homeinto' }});
    }
  }
}


onMounted(() => {

  // getCode()
})







</script>


<style lang="scss" scoped>
.container {
  background: #f9f9f9;
  overflow: hidden;
  margin-bottom: 45px;
  height: 100%;
}

.navbar {
  position: fixed;
  top: 0;
  width: 100%;
  background-color: #fff;
}

.addbtn {
  position: fixed;
  bottom: 1rem;
  width: 92%;
  left: 4%;
}

.van-form {
  background: #fff;
}
</style>